import {FileTransferObject} from '@ionic-native/file-transfer';
import {File} from '@ionic-native/file';
import {FileOpener} from "@ionic-native/file-opener";
import {Log} from "./Log";
import {
    Loading,
    LoadingController, ModalController,
    Platform,
    Toast

} from "ionic-angular";
import {Utils} from "./Utils";
import {ShowpdfPage} from "../../pages/showpdf/showpdf";
import {GalleryModal} from "ionic-gallery-modal";

export class FilePreview {
    public loading: Loading;
    private pageType: string;
    private fn: Function;
    private toast: Toast = null;
    imageArray: any[] = [];
    private photos: any[] = [];
    constructor(
        public modalCtrl:ModalController,
        public loadingCtrl: LoadingController,
        public platform: Platform,
        private fileTransfer: FileTransferObject,
        private file: File,
        private fileOpener: FileOpener) {

    }

    onView(item) {

        //文件路径
        var filePath = item.FuJianLJ;
        //获取最后一个.的位置
        var index= filePath.lastIndexOf(".");
        //获取后缀
        var ext = filePath.substr(index+1);
        if(ext ==='pdf'){
            this.checkUrl(filePath);
        }else if(Utils.isAssetTypeAnImage(ext)) {
            this.imageArray.push(item.FuJianLJ);
            this.openModal();
        }else{
            this.download(item.FuJianMC,item.FuJianLJ,ext);

        }


    }
    checkUrl(url) {
        let modal = this.modalCtrl.create(ShowpdfPage, {
            url: url
        });
        modal.present();
    }
    openModal() {

        this.changeArrayToGallery(this.imageArray);
        let modal = this.modalCtrl.create(GalleryModal, {

            photos: this.photos,

            initialSlide: 1,

        });

        modal.present();

    }



    changeArrayToGallery(array) {
        for (let i = 0; i < array.length; i++) {
            var object = { "url": array[i]};
            this.photos.push(object);
        }
    }

    download(name, url, ext) {
        this.showLoading(true, '正在加载中');
        let that = this;
        let target: string = this.file.dataDirectory + name;
        that.fileTransfer.download(url, target).then((entry) => {
            //that.openFile(target, ext)
        }, (error) => {

        });
        this.fileProgress(target, ext);
    }

    /**
     * 打开文件
     * @param path
     */
    private openFile(path, ext) {
        this.fileOpener.open(path, this.getFileMimeType(ext))
            .then(() => console.log('File is opened'))
            .catch(e => console.log(e));
    }

    private fileProgress(path, ext) {
        let that = this;

        this.fileTransfer.onProgress(progressEvent => {
            if (progressEvent.lengthComputable) {
                // 下载过程会一直打印，完成的时候会显示 1
                Log.w('file progress loading...', progressEvent.loaded / progressEvent.total);
                let num: any = progressEvent.loaded / progressEvent.total;
                if (num == 1) {
                    //alert('下载进度:' + num)
                    that.showLoading(false, '');
                    that.openFile(path, ext)
                }
            } else {

            }
        });
    }

    private getFileMimeType(fileType) {
        let mimeType: any = '';

        switch (fileType) {
            case 'txt':
                mimeType = 'text/plain';
                break;
            case 'docx':
                mimeType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
                break;
            case 'doc':
                mimeType = 'application/msword';
                break;
            case 'pptx':
                mimeType = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
                break;
            case 'ppt':
                mimeType = 'application/vnd.ms-powerpoint';
                break;
            case 'xlsx':
                mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                break;
            case 'xls':
                mimeType = 'application/vnd.ms-excel';
                break;
            case 'zip':
                mimeType = 'application/x-zip-compressed';
                break;
            case 'rar':
                mimeType = 'application/octet-stream';
                break;
            case 'pdf':
                mimeType = 'application/pdf';
                break;
            case 'jpg':
                mimeType = 'image/jpeg';
                break;
            case 'png':
                mimeType = 'image/png';
                break;
            default:
                mimeType = 'application/' + fileType;
                break;
        }
        return mimeType;
    }

    private showLoading(showLoadingUI: boolean, text: string) {
        console.log("BasePage", "showLoading: showLoadingUI= " + showLoadingUI + "    " + this.constructor.name);

        if (showLoadingUI) {
            if (!this.loading) {
                this.fn = this.platform.registerBackButtonAction(() => {
                    Log.d("BasePage", "showLoading  拦截 返回键");
                }, 101);
                this.loading = this.loadingCtrl.create({
                    spinner: "ios",
                    content: text
                });
                Log.d("BasePage", "showLoading: show");

                this.loading.present().catch((err) => {
                    Log.d("BasePage", "showLoading: err");

                });
            }
        } else {
            if (this.fn) {
                Log.d("BasePage", "showLoading  取消拦截 返回键");
                this.fn();
                this.fn = null;
            }
            if (this.loading) {
                Log.d("BasePage", "showLoading: dismiss");
                this.loading.dismiss().catch((err) => {
                    Log.d("BasePage", "showLoading: err");

                });
                this.loading = null;
            }
        }
    }
}
